package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.request.PrdFeedRequest;
import com.wonder.app.request.SfcOptrptRequest;
import com.wonder.app.service.*;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.MapToEntity;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PrdFeedServiceImpl extends ServiceImpl<PrdFeedDao,  PrdFeed> implements PrdFeedService {
    private static final Logger _logger = LoggerFactory.getLogger(PrdFeedServiceImpl.class);
    @Autowired
    private PrdFeedService prdFeedService;
    @Autowired
    private  PrdFeedDao prdFeedDao;
    @Autowired
    private PrdFeedDetailDao prdFeedDetailDao;
    @Autowired
    private MaterialService materialService;
    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;

    @Autowired
    private SfcProplanDao sfcProplanDao;


    @Autowired
    private PickDetailService pickDetailService;

    @Autowired
    private PpBomDao ppBomDao;

    @Autowired
    private TrayService trayService;

    @Autowired
    private SfcproplanDetailDao sfcproplanDetailDao;

    @Autowired
    private PrdFeedDetailService prdFeedDetailService;

    @Override
    public IPage<PrdFeed> selectList(PrdFeedRequest prdFeedRequest, Page<PrdFeed> page) {
        LambdaQueryWrapper<PrdFeed> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (prdFeedRequest.getFBillNo() != null){
            lambdaQueryWrapper.like(PrdFeed::getFBillNo,prdFeedRequest.getFBillNo());
        }

        if (prdFeedRequest.getFKDBILLNO() != null){
            lambdaQueryWrapper.like(PrdFeed::getFKDBILLNO,prdFeedRequest.getFKDBILLNO());
        }

        if (prdFeedRequest.getFBILLNOMO() != null){
            lambdaQueryWrapper.like(PrdFeed::getFBILLNOMO,prdFeedRequest.getFBILLNOMO());
        }

        if (prdFeedRequest.getFCREATEUSER() != null){
            lambdaQueryWrapper.like(PrdFeed::getFCREATEUSER,prdFeedRequest.getFCREATEUSER());
        }


        if (prdFeedRequest.getFDATE() != null){
            Date[] orderDate = prdFeedRequest.getFDATE();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(PrdFeed::getFDATE, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(PrdFeed::getFDATE,orderDate[1]);

        }
        lambdaQueryWrapper.orderByDesc(PrdFeed::getFDATE);
        Page<PrdFeed> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }

    /**
     * 生产补料单明细详情
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getPrdFeedDetail(Map<String, Object> map) {
        String billNo = map.get("billNo").toString();
        PrdFeed prdfeedform = prdFeedDao.selectOne(new LambdaQueryWrapper<PrdFeed>()
                .eq(PrdFeed::getFBillNo,billNo));
        List<PrdFeedDetail> prdfeeddetailList = prdFeedDetailDao.selectList(new LambdaQueryWrapper<PrdFeedDetail>()
                .eq(PrdFeedDetail::getFBILLNO,billNo));
        Map<String,Object> data = new HashMap<>();
        data.put("data",prdfeedform);
        data.put("dataList",prdfeeddetailList);
        return data;
    }

    /**
     * 创建补料单
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createFeedBill(Long userId,String userName, Map<String, Object> map) throws Exception {
        Map<String,Object> planData = VtuzxUtil.getObject(map,"planData");
        List<Map<String,Object>> detailList = VtuzxUtil.getObject(map,"detail");
        String PickBillNo =  IXqcConst.createBillNo(BillType.SCBL);//生成中台补料单号
        String FBILLNOMO = VtuzxUtil.getString(map,"moBillNo");//生产订单号
        String inStockTime = VtuzxUtil.getString(map,"inStockTime");//单据日期
        String BIllNo = VtuzxUtil.getString(map,"billNo");//工序计划单号
        //获取车间信息
        List<SfcproplanDetail> sfcproplanDetailList = sfcproplanDetailDao.selectList(new LambdaQueryWrapper<SfcproplanDetail>()
                .eq(SfcproplanDetail::getBillNo, BIllNo));
        String workNo = "";
        String workName = "";
        if(!VtuzxUtil.isEmpty(sfcproplanDetailList)){
            workName = sfcproplanDetailList.get(0).getDepartName();
            workNo = sfcproplanDetailList.get(0).getDepartNo();

        }

        List<PrdFeedDetail> feedDetailList = new ArrayList<>();

        for (Map<String,Object> data : detailList ){
            PrdFeedDetail feedDetail = MapToEntity.mapToBean(data,PrdFeedDetail.class);
            feedDetail.setTEMP(false);
            feedDetail.setFBILLNO(PickBillNo);//领料单号
            feedDetailList.add(feedDetail);
        }

        PrdFeed prdFeed = new PrdFeed();
        prdFeed.setFERPNO(BIllNo);
        prdFeed.setFBillNo(PickBillNo);
        prdFeed.setFDATE(DateUtils.strToDate(inStockTime,"yyyy-MM-dd"));
        prdFeed.setCreateTime(new DateTime());
        prdFeed.setFCREATEUSER(userName);
        prdFeed.setFSTATE(false);
        prdFeed.setFBILLNOMO(FBILLNOMO);//生产订单单号



        //机加车间传金蝶领料单，毛坯车间传金蝶调拨单
        if (workName.contains("机加")){
            try {
                syncKingdeeOrderService.syncPrdPickByFeed(userId,prdFeed,feedDetailList);
            } catch (Exception e){
                _logger.info(e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
            //领料单创建一个为了机加打印时用
            for (PrdFeedDetail detail : feedDetailList){
                PickDetail pickDetail = new PickDetail();
                pickDetail.setFMATERIALNUMBER(detail.getFMATERIALNUMBER());
                pickDetail.setFMATERIALNAME(detail.getFMATERIALNAME());
                pickDetail.setFSPECIFICATION(detail.getFSPECIFICATION());
                pickDetail.setFUNITNAME(detail.getFUNITNAME());
                pickDetail.setFUNITID(detail.getFUNITID());
                pickDetail.setFINFACTQTY(detail.getFACTUALQTY());//领料数量
                pickDetail.setFLOT(detail.getFLOT());
                pickDetail.setTRAYNO(detail.getTRAYNO());
                pickDetail.setTEMP(false);
                pickDetail.setMOBILLNO(detail.getMOBILLNO());
                pickDetail.setCREATETIME(new Date());
                pickDetail.setISPPBOM(true);
                pickDetail.setISPRINT(false);
                pickDetail.setWORKSHOPNAME("机加车间");
                pickDetail.setFBILLNO(detail.getFBILLNO());
                pickDetailService.save(pickDetail);
            }
        } else {//传调拨单
            try {
                syncKingdeeOrderService.syncAllocationByFeed(userId,prdFeed,feedDetailList);
            } catch (Exception e){
                _logger.info(e.getMessage());
            }
        }
        //保存到数据库
        boolean savehead = prdFeedService.save(prdFeed);
        boolean saveBatch = prdFeedDetailService.saveOrUpdateBatch(feedDetailList);

        return savehead && saveBatch;
    }

    /**
     * 删除补料详情中的临时数据
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean deleteFeedDetailTemp(String userName, Map<String, Object> map) throws Exception {
        int detailId = VtuzxUtil.getInt(map,"id");
        PrdFeedDetail feedDetail = prdFeedDetailService.getById(detailId);
        //需要删除已经生生成的托盘信息
        if (!VtuzxUtil.isEmpty(feedDetail.getTRAYNO())){
            trayService.remove(new LambdaQueryWrapper<Tray>()
                    .eq(Tray::getFBILLNO,feedDetail.getTRAYNO()));
        }

        //删除临时表中的数据
        boolean b = prdFeedDetailService.removeById(detailId);
        return b;
    }

    /**
     * 包装间生成补料单
     * @param userName
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public String createFeedBillPackage(Long user_id, String userName,SfcOptrptPackage sfcOptrptPackage, String type) throws Exception {

        List<PrdFeedDetail> feedDetailList = new ArrayList<>();
        String PickBillNo =  IXqcConst.createBillNo(BillType.SCBL);//生成中台补料单号
        String FBILLNOMO = sfcOptrptPackage.getMoBillNo();//生产订单号
        //报废类型退料数量为报废数量，仓库为包装材料库
        //外协不良类型退料数量为外协不良数量，仓库为包装材料库
        //返修类型退料数量为返修数量，仓库为包装材料库
        Double count = 0.0;

        if ("fail".equals(type)){
            count = sfcOptrptPackage.getFailQty();
        }
//        else if ("out".equals(type)){
//            count = sfcOptrptPackage.getOutFailQty();
//        } else if ("return".equals(type)){
//            count = sfcOptrptPackage.getReturnQty();
//
//        }
        List<String> materialNoList = new ArrayList<>();
        materialNoList.add(sfcOptrptPackage.getMaterialNo());
        //根据物料编码查询物料名称等信息
        List<Map<String, Object>> materialList = materialService.getMaterialByNo(materialNoList);
        if (VtuzxUtil.isEmpty(materialList)){
            throw new RuntimeException(String.format("物料编码:%s不存在",sfcOptrptPackage.getMaterialNo()));
        }
        //将查询到的物料信息转成map
        Map<String, Object> materialToMap = changeMaterialToMap(materialList);
        Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,sfcOptrptPackage.getMaterialNo());


        PrdFeedDetail prdFeedDetail = new PrdFeedDetail();
        prdFeedDetail.setFBILLNO(PickBillNo);
        prdFeedDetail.setFMATERIALNUMBER(sfcOptrptPackage.getMaterialNo());
        prdFeedDetail.setFMATERIALNAME(VtuzxUtil.getString(materialMap,"FNAME"));
        prdFeedDetail.setFSPECIFICATION(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
        prdFeedDetail.setFUNITID(VtuzxUtil.getString(materialMap,"unitNo"));
        prdFeedDetail.setFUNITNAME(VtuzxUtil.getString(materialMap,"unitName"));
        prdFeedDetail.setFACTUALQTY(count);//实发数量
        prdFeedDetail.setFSTOCKNAME("包装材料库");
        prdFeedDetail.setFSTOCKNUMBER("CK020");
        prdFeedDetail.setMOBILLNO(FBILLNOMO);
        prdFeedDetail.setTEMP(false);
        prdFeedDetail.setISPPBOM(true);
        feedDetailList.add(prdFeedDetail);

        PrdFeed prdFeed = new PrdFeed();
        prdFeed.setFBillNo(PickBillNo);
        prdFeed.setFDATE(new DateTime());
        prdFeed.setFCREATEUSER(userName);
        prdFeed.setFSTATE(false);
        prdFeed.setFBILLNOMO(FBILLNOMO);//生产订单单号


        //保存到数据库
        boolean savehead = prdFeedService.saveOrUpdate(prdFeed);
        boolean saveBatch = prdFeedDetailService.saveOrUpdateBatch(feedDetailList);

        String kingdeeBillNo = "";
        try {
            kingdeeBillNo = syncKingdeeOrderService.syncprdfeed(user_id,prdFeed,feedDetailList,sfcOptrptPackage);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());

        }

        return kingdeeBillNo;
    }

    /**
     * 添加补料临时数据
     * @param userName
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createFeedTemp(String userName, Map<String, Object> map) throws Exception {
        String operNo = VtuzxUtil.getString(map,"operNo");//工单号
        Map<String,Object> trayData = VtuzxUtil.getObject(map,"trayData");
        String itemnumber = VtuzxUtil.getString(trayData,"itemnumber");//件号
        String stockNo = VtuzxUtil.getString(trayData,"stockNo");//仓库
        String mateiralNo = VtuzxUtil.getString(trayData,"mateiralNo");//物料编码
        String flot = VtuzxUtil.getString(trayData,"flot");//批号
        double fqty = VtuzxUtil.getDouble(trayData,"fqty");//数量
        List<SfcproplanDetail> sfcproplanDetailList = sfcproplanDetailDao.selectList(new LambdaQueryWrapper<SfcproplanDetail>()
                .eq(SfcproplanDetail::getBillNo, operNo));
        String departName = sfcproplanDetailList.get(0).getDepartName();//车间名称
        SfcProplan sfcProplan = sfcProplanDao.selectOne(new LambdaQueryWrapper<SfcProplan>()
                .eq(SfcProplan::getBillNo, operNo));
        if (VtuzxUtil.isEmpty(mateiralNo)){
            throw new RuntimeException("请输入物料编码");
        }
        List<String> materialNoList = new ArrayList<>();
        materialNoList.add(mateiralNo);
        //根据物料编码查询物料名称等信息
        List<Map<String, Object>> materialList = materialService.getMaterialByNo(materialNoList);
        if (VtuzxUtil.isEmpty(materialList)){
            throw new RuntimeException(String.format("物料编码:%s不存在",mateiralNo));
        }
        //将查询到的物料信息转成map
        Map<String, Object> materialToMap = changeMaterialToMap(materialList);
        Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,mateiralNo);
        //如果是机加车间的需要生成托盘,毛坯不用生成
        if (departName.contains("机加")){
            Map<String,Object> trayMap = new HashMap<>();
            trayMap.put("itemnumber",mateiralNo);
            trayMap.put("flot",flot);
            trayMap.put("inStockTime","2025-09-18 00:00:00");
            trayMap.put("fqty",fqty);
            trayMap.put("operNo",operNo);
            String trayPda = trayService.createTrayPdaByFeed(trayMap, userName);//新增的托盘号
            //生成补料单临时数据
            PrdFeedDetail prdFeedDetail = new PrdFeedDetail();
            prdFeedDetail.setFMATERIALNUMBER(mateiralNo);
            prdFeedDetail.setFMATERIALNAME(VtuzxUtil.getString(materialMap,"FNAME"));
            prdFeedDetail.setFSPECIFICATION(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
            prdFeedDetail.setFUNITNAME(VtuzxUtil.getString(materialMap,"unitName"));
            prdFeedDetail.setFUNITID(VtuzxUtil.getString(materialMap,"unitNo"));
            prdFeedDetail.setFACTUALQTY(fqty);//实发数量
            prdFeedDetail.setFLOT(flot);
            prdFeedDetail.setTRAYNO(trayPda);
            prdFeedDetail.setTEMP(true);
            prdFeedDetail.setMOBILLNO(sfcProplan.getMoBillNo());
            prdFeedDetail.setCREATETIME(new Date());
            prdFeedDetail.setFSTOCKNUMBER(stockNo);
            prdFeedDetailService.save(prdFeedDetail);
            //领料也先添加一个(为了打印用)
//            PickDetail pickDetail = new PickDetail();
//            pickDetail.setFMATERIALNUMBER(mateiralNo);
//            pickDetail.setFMATERIALNAME(VtuzxUtil.getString(materialMap,"FNAME"));
//            pickDetail.setFSPECIFICATION(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
//            pickDetail.setFUNITNAME(VtuzxUtil.getString(materialMap,"unitName"));
//            pickDetail.setFUNITID(VtuzxUtil.getString(materialMap,"unitNo"));
//            pickDetail.setFINFACTQTY(fqty);//领料数量
//            pickDetail.setFLOT("TY");
//            pickDetail.setTRAYNO(trayPda);
//            pickDetail.setTEMP(false);
//            pickDetail.setMOBILLNO(sfcProplan.getMoBillNo());
//            pickDetail.setCREATETIME(new Date());
//            pickDetail.setISPPBOM(true);
//            pickDetail.setISPRINT(false);
//            pickDetail.setWORKSHOPNAME("机加车间");
//            pickDetailService.save(pickDetail);
        } else {
            //如果是铸造车间的生成补料详情数据
            PrdFeedDetail prdFeedDetail = new PrdFeedDetail();
            prdFeedDetail.setFMATERIALNUMBER(mateiralNo);
            prdFeedDetail.setFMATERIALNAME(VtuzxUtil.getString(materialMap,"FNAME"));
            prdFeedDetail.setFSPECIFICATION(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
            prdFeedDetail.setFUNITNAME(VtuzxUtil.getString(materialMap,"unitName"));
            prdFeedDetail.setFUNITID(VtuzxUtil.getString(materialMap,"unitNo"));
            prdFeedDetail.setFACTUALQTY(fqty);//实发数量
            prdFeedDetail.setFLOT("TY");
//            prdFeedDetail.setTRAYNO(trayPda);
            prdFeedDetail.setTEMP(true);
            prdFeedDetail.setMOBILLNO(sfcProplan.getMoBillNo());
            prdFeedDetail.setCREATETIME(new Date());
            prdFeedDetail.setFSTOCKNUMBER(stockNo);
            prdFeedDetailService.save(prdFeedDetail);
        }

        return null;
    }
    /**
     * key;物料编码 val:物料相关信息(map)
     * @param materialList
     * @return
     */
    private Map<String,Object> changeMaterialToMap(List<Map<String,Object>> materialList){
        Map<String,Object> dataMap = new HashMap<>();
        for (Map<String,Object> data : materialList){
            String FNUMBER = VtuzxUtil.getString(data,"FNUMBER");
            String FNAME = VtuzxUtil.getString(data,"FNAME");
            String FSPECIFICATION = VtuzxUtil.getString(data,"FSPECIFICATION");
            String unitNo = VtuzxUtil.getString(data,"unitNo");//单位编码
            String unitName = VtuzxUtil.getString(data,"unitName");//单位名称
            String FDOCUMENTSTATUS = VtuzxUtil.getString(data,"FDOCUMENTSTATUS");//审核状态
            String FFORBIDSTATUS = VtuzxUtil.getString(data,"FFORBIDSTATUS");//禁用状态
            Map<String,Object> materialMap = new HashMap<>();
            materialMap.put("FNUMBER",FNUMBER);
            materialMap.put("FNAME",FNAME);
            materialMap.put("FSPECIFICATION",FSPECIFICATION);
            materialMap.put("unitNo",unitNo);
            materialMap.put("unitName",unitName);
            materialMap.put("FDOCUMENTSTATUS",FDOCUMENTSTATUS);
            materialMap.put("FFORBIDSTATUS",FFORBIDSTATUS);
            dataMap.put(FNUMBER,materialMap);
        }
        return dataMap;
    }

}

